package main

import (
	"github.com/gocolly/colly"
	"fmt"
	"strings"
	"strconv"
	"math"
	"github.com/PuerkitoBio/goquery"
	"time"
	"match-spider/util/http"
	"github.com/xuri/excelize"
	"math/rand"
	"reflect"
	"github.com/robertkrimen/otto"
	"encoding/json"
	"match-spider/util/format"
)
const (
	SCHEDULE_URI="http://61.143.224.154:8071/phone/schedule_0_0.txt"

)
var totalLine=0
func schedule(fn func([]interface{},int))  {

	params := map[string]string{
		"an":"iosQiuTan",
		"av":"6.5",
		"from":"2",
		"r":strconv.FormatInt(time.Now().Unix(),10),
	}
	http.Get(SCHEDULE_URI, params, func(body string) {
		s:=strings.Split(body,"$$")
		leagueString:=s[0]
		matchString:=s[1]
		leagueMap:=make(map[string]string)
		leagues:=strings.Split(leagueString,"!")
		//将联赛放入map
		for _,v:=range leagues {
			slice:=strings.Split(v,"^")
			leagueMap[slice[1]]=slice[0]
		}

		matchs:=strings.Split(matchString,"!")
		i:=0
		for _,v:=range matchs {

			slice:=strings.Split(v,"^")
			matchId:=slice[0]
			league:=leagueMap[slice[1]]
			startAt:=slice[3]
			teamA:=slice[5]
			teamB:=slice[6]

			lastmatchFetch(matchId,league,startAt,teamA,teamB,fn)
			i++
			seed:=2000+rand.Intn(1000)
			time.Sleep(time.Millisecond*time.Duration(seed))
		}


	}, func(err error) {
		fmt.Println("schedule",err)
	})
}
func fetchMatch(date string,fn func([]interface{},int))  {
	ss:=",英超,英冠,德甲,德乙,法甲,意甲,西甲,葡超,"
	url:="http://bf.win007.com/Over_matchdate.aspx?matchdate="+date

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnHTML("#table_live", func(e *colly.HTMLElement) {

		e.DOM.Find("tr").Each(func(i int, s *goquery.Selection){
			d := s.Find("td").Eq(9)
			text, b := d.Find("a").Eq(0).Attr("onclick")
			if b {
				id := strings.Replace(text, "analysis(", "", -1)
				id = strings.Replace(id, ")", "", -1)
				league := s.Find("td").Eq(0).Text()
				datetime:=s.Find("td").Eq(1).Text()
				homeTeam:=s.Find("td").Eq(3).Text()
				//d3 := s.Find("td").Eq(4)
				//homeScore := d3.Find("font").Eq(0).Text()
				//guestSocre := d3.Find("font").Eq(1).Text()
				guestTeam:=s.Find("td").Eq(5).Text()
				//asiaOdds:=s.Find("td").Eq(7).Text()
				//underOverOdds := s.Find("td").Eq(8).Text()
				//fmt.Println(datetime,id,league,date,homeTeam,homeScore,guestTeam,guestSocre,asiaOdds,underOverOdds)
				//m:=id+"^"+league+"^"+datetime+"^"+homeTeam+"^"+homeScore+"^"+guestTeam+"^"+guestSocre+"^"+asiaOdds+"^"+underOverOdds
				if strings.Contains(ss,","+league+","){
					lastmatchFetch(id,league,datetime,homeTeam,guestTeam,fn)
				}

			}

		})
	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)
	})

	c.Visit(url)
}
func checkAsiaData(data string) (bool,[]float64) {
	asiaSlice:=strings.Split(data,"!")

	//开盘公司至少10家
	size:=len(asiaSlice)
	if size<10{
		return false,nil
	}
	//初盘盘口-0.25~0.25
	i:=int(0)
	j:=int(0)
	m:=int(0)
	len:=int(0)
	//初盘均值
	s1:=float64(0)
	//终盘均值
	s2:=float64(0)
	oddsData:=make(map[string][]string)
	asia0:=make(map[string]int64)
	asia:=make(map[string]int64)
	a:=float64(-9999)
	b:=float64(-9999)
	c:=float64(-9999)


	for _,v:=range asiaSlice{
		asiaOdds:=strings.Split(v,"^")
		name:=asiaOdds[0]
		if name=="Crown"||name=="ＳＢ"{
			a,_=strconv.ParseFloat(asiaOdds[5],64)
			b,_=strconv.ParseFloat(asiaOdds[6],64)
			c,_=strconv.ParseFloat(asiaOdds[7],64)
		}

		odds,_:=strconv.ParseFloat(asiaOdds[3],64)
		odds2,_:=strconv.ParseFloat(asiaOdds[6],64)
		s1=s1+odds
		s2=s2+odds2
		if math.Abs(odds)!=1&&math.Abs(odds)!=0.75&&math.Abs(odds)!=0.5{
			i++
		}
		if odds==odds2&&odds2==0{
			//初盘，终盘不能全都是0盘口不变化
			j++
		}
		if math.Abs(odds2)!=1&&math.Abs(odds2)!=0.75&&math.Abs(odds2)!=0.5{
			//终盘不在范围的去掉
			m++
		}
		//以终盘中大众盘口作为最终终盘口
		if asia[asiaOdds[6]]==0{
			asia[asiaOdds[6]]=1
		}else{
			asia[asiaOdds[6]]=asia[asiaOdds[6]]+1
		}
		if asia0[asiaOdds[3]]==0{
			asia0[asiaOdds[3]]=1
		}else{
			asia0[asiaOdds[3]]=asia0[asiaOdds[3]]+1
		}
		oddsData[name]=asiaOdds
		len++
	}


	//初盘
	n0:=float64(-9999)
	temp0:=int64(0)
	//终盘
	n:=float64(-9999)
	temp:=int64(0)
	for k,v:=range asia0{
		if v>temp0{
			temp0=v
			n0,_=strconv.ParseFloat(k,64)

		}
	}
	for k,v:=range asia{
		if v>temp{
			temp=v
			n,_=strconv.ParseFloat(k,64)

		}
	}
	return true,[]float64{
		a,b,c,n0,n,s1/float64(len),s2/float64(len),
	}
}

func asiaFetch(id string,fn func(string))  {
	seed:=500+rand.Intn(500)
	time.Sleep(time.Millisecond*time.Duration(seed))
	url:="http://121.10.245.46:8072/phone/Handicap.aspx?ID="+id+"&an=iosQiuTan&av=6.5&from=2&lang=0&r="

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnResponse(func(response *colly.Response) {
		content:=string(response.Body)
		fn(content)

	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		//fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)

	})

	c.Visit(url)
}
func europeFetch(id string,fn func(string))  {
	seed:=500+rand.Intn(500)
	time.Sleep(time.Millisecond*time.Duration(seed))
	url:="http://1x2.nowscore.com/" +id + ".js"
	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnResponse(func(response *colly.Response) {
		content:=string(response.Body)
		vm := otto.New()
		vm.Run(content)
		game,_:=vm.Get("game")
		//gameDetail,_:=vm.Get("gameDetail")
		gameValue,_:=game.Export()
		//gameDetailValue,_:=gameDetail.Export()
		t:=reflect.TypeOf(gameValue)
		if strings.Compare(t.String(),"[]interface {}")==0{
			fn("")
			return
		}

		gameSlice:=make([]string,0)
		for _,v:=range gameValue.([]string) {

			if strings.Contains(v,"易胜博(安提瓜和巴布达)")||
				strings.Contains(v,"伟德(直布罗陀)")||
				strings.Contains(v,"威廉希尔(英国)")||
				strings.Contains(v,"明陞(菲律宾)")||
				strings.Contains(v,"利记sbobet(英国)")||
				strings.Contains(v,"立博(英国)")||
				strings.Contains(v,"金宝博(马恩岛)")||
				strings.Contains(v,"SB")||
				strings.Contains(v,"Interwetten(塞浦路斯)")||
				strings.Contains(v,"bet 365(英国)")||
				strings.Contains(v,"竞彩官方")||
				strings.Contains(v,"澳门")||
				strings.Contains(v,"Oddset(德国)")||
				strings.Contains(v,"SNAI(意大利)")||
				strings.Contains(v,"香港马会(中国香港)"){
				gameSlice=append(gameSlice, v)
			}

		}


		gameJson,_:=json.Marshal(gameSlice)
		fn(string(gameJson))

	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		//fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)

	})

	c.Visit(url)
}

func lastmatchFetch(id string,league string,startAt string,t1 string,t2 string,fn func([]interface{},int))  {
	seed:=500+rand.Intn(500)
	time.Sleep(time.Millisecond*time.Duration(seed))
	index1:=id[0:1]
	index2:=id[1:3]
	url:="http://61.143.224.156:8071/phone/analysis/"+index1+"/"+index2+"/cn/"+id+".htm?an=iosQiuTan&av=6.5&from=2&r="

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnResponse(func(response *colly.Response) {
		content := string(response.Body)
		if strings.Compare(strings.TrimSpace(content),"")==0{
			fmt.Println("Error","Content Empty")
		}else {
			asiaFetch(id,func(data string) {

				e, fa:= checkAsiaData(data)
				if (!e) {
					//fmt.Println("Error","Not fit")
					return
				}
				e1,ff:=format.FormatData(id,league,startAt,t1,t2,content,"")
				if !e1{
					//fmt.Println("Error","Have no data")
					return
				}
				totalLine++
				slice:=[]interface{}{id,startAt,league,t1,t2,fa[0], fa[1], fa[2], fa[3], fa[4], fa[5],
					fa[6],}
				for _,v:=range ff{
					for _,vv:=range v {
						slice=append(slice,vv)
					}


				}
				fmt.Println(id,startAt,league,t1,t2)

				fn(slice, totalLine)

			})

		}
	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		//fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)

	})

	c.Visit(url)
}

func main()  {
	//fetchMatch("2018-1-19");
	/*data:=[][]string{
		[]string{"1490877","卡塔尔联","","阿拉比SC","艾杜哈尼"},
		[]string{"1483432","印度超","","东北联","泰坦"},
		[]string{"1418068","土超","","卡斯帕萨","阿兰亚斯堡"},
		[]string{"1395653","荷甲","","乌德勒支","艾克马亚"},
	}
	for _,v:=range data {
		lastmatchFetch(v[0],v[1],v[2],v[3],v[4])
	}*/

	e:=[]string{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
	xlsx := excelize.NewFile()

	categories := []string{

	}
	for k,v:=range categories{
		len:=int(k/26)
		s:=""
		if len>0{
			s+=e[len-1]+e[k%26]
		}else{
			s+=e[k%26]
		}

		xlsx.SetCellValue("Sheet1",s+"1", v)
	}
	fetchMatch("2018-02-23",func(s []interface{}, i int) {
		for k,v:=range s{
			len:=int(k/26)
			s:=""
			if len>0{
				s+=e[len-1]+e[k%26]
			}else{
				s+=e[k%26]
			}
			xlsx.SetCellValue("Sheet1",s+strconv.Itoa(i+1), v)
		}
	})
	err := xlsx.SaveAs("./data.xlsx")
	if err != nil {
		fmt.Println(err)
	}
}